package com.ysccc.shares.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ysccc.shares.entity.Shares;
import com.ysccc.shares.entity.SharesDaily;
import com.ysccc.shares.manager.SharesDailyManager;
import com.ysccc.shares.manager.SharesManager;
import com.ysccc.shares.service.SharesService;
import com.ysccc.shares.web.vo.SharesAddVo;
import com.ysccc.shares.web.vo.SharesEditVo;
import com.ysccc.shares.web.vo.SharesVo;
import com.ysccc.spring.boot.starter.sqldb.repository.support.FilterParamBuilder;
import com.ysccc.spring.boot.starter.web.commons.builder.JsonBuilder;
import com.ysccc.spring.boot.starter.web.commons.builder.JsonBuilder.JsonData;
import com.ysccc.spring.boot.starter.web.commons.builder.JsonBuilder.JsonPage;
import com.ysccc.spring.boot.starter.web.commons.builder.WebRequestBuilder;

@RestController
@RequestMapping("/shares")
public class SharesController {
	
	@Autowired
	private SharesManager sharesManager;
	
	@Autowired
	private SharesService sharesService;
	
	@Autowired
	private SharesDailyManager sharesDailyManager;

	@PostMapping("/page")
	public JsonPage page(HttpServletRequest request) {
		WebRequestBuilder builder = WebRequestBuilder.of(request).build();
		Page<Shares> page = sharesManager.findPage(builder.getFilters(), builder.getPageable());
		return JsonBuilder.of(page.map(SharesVo::new)).build(JsonPage.class);
	}
	
	@PostMapping("/add")
	public JsonData add(@RequestBody SharesAddVo vo) {
		sharesService.add(vo);
		return JsonBuilder.of().build(JsonData.class);
	}
	
	@PutMapping("/edit")
	public JsonData edit(@RequestBody SharesEditVo vo) {
		sharesService.edit(vo);
		return JsonBuilder.of().build(JsonData.class);
	}
	
	@DeleteMapping("/delete/{id}")
	public JsonData edit(@PathVariable Long id) {
		List<SharesDaily> dailies = sharesDailyManager.findList(FilterParamBuilder.create().eq("shares.id", id).build());
		sharesDailyManager.delete(dailies);
		sharesManager.delete(id);
		return JsonBuilder.of().build(JsonData.class);
	}
}
